package com.gz.logistics.app;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;
import com.gz.logistics.R;

public class BluetoothActivity extends BaseActivity {


	private final static int REQUEST_CONNECT_DEVICE = 1; // 跳转页面请求码
	private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; // SPP服务UUID号

	private InputStream is; // 输入流，用来接收蓝牙数据

	BluetoothDevice _device = null; // 蓝牙设备
	BluetoothSocket _socket = null; // 蓝牙通信socket
	boolean bRun = true;
	boolean bThread = false;
	boolean flag = false, flag_time_cancel = false, flag_set_time = false;
	private double money = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setActionbarTitle("POS闪付", false);
		String online_money = this.getIntent().getStringExtra("money");
		money = Double.parseDouble(online_money);
		setContentView(R.layout.activity_test);
	}


	//按钮点击事件
	public void send(View v) {

		m.put("res", "err");//默认res
		openBluetooth(money);//蓝牙支付方法  参数传钱
		if (i==0) {
			receThread.start();
			i++;
		}

	}

	int i = 0;

	//接收返回数据的线程 返回的是map集合
	public  Thread receThread = new Thread(){
		public void run() {
			while (true) {
				try {
					sleep(1500);

					// 返回的是map集合m 	参数  res: String key ;	backData String value返回值
					if (!m.get("res").equals("err")) {
						String backData = m.get("res");

						//break;//将break删掉
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
	};

	// 获取本地蓝牙
	BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();

	public void connect(View v) {
		openBluetooth(0);
	}


	double app;

	// 打开蓝牙并跳转到搜索界面
	public void openBluetooth(double hhe) {
		app = hhe;
		// 如果打开本地蓝牙设备不成功，提示信息，结束程序
		if (_bluetooth == null) {
			Toast.makeText(this, "无法打开手机蓝牙，请确认手机是否有蓝牙功能！", Toast.LENGTH_LONG)
					.show();
		}
		if (_bluetooth.isEnabled() == false) { // 如果蓝牙服务不可用则提示
			// 打开蓝牙
			_bluetooth.enable();
			Toast.makeText(this, "正在开启蓝牙...", Toast.LENGTH_LONG).show();
		}
		// 如未连接设备则打开DeviceListActivity进行设备搜索
		if (_socket == null) {
			Intent serverIntent = new Intent(this, DeviceListActivity.class); // 跳转页面
			startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); // 意图对象和请求码
		} else {
			System.out.println("_bluetooth.getState()" + _bluetooth.getState());

			// 关闭连接socket
			try {

				is.close();
				_socket.close();
				_socket = null;
				flag = false; // 连接标志位

			} catch (Exception e) {
			}

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case REQUEST_CONNECT_DEVICE: // 连接结果，由DeviceListActivity设置返回
				// 响应返回结果
				if (resultCode == Activity.RESULT_OK) { // 连接成功，由DeviceListActivity设置返回
					// MAC地址，由DeviceListActivity设置返回
					String address = data.getExtras().getString(
							DeviceListActivity.EXTRA_DEVICE_ADDRESS);
					// 得到蓝牙设备
					_device = _bluetooth.getRemoteDevice(address);

					// 用服务号得到socket
					try {
						_socket = _device.createRfcommSocketToServiceRecord(UUID
								.fromString(MY_UUID));
					} catch (IOException e) {
						Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
					}
					// 连接socket
					try {
						_socket.connect();
						Toast.makeText(this, "连接" + _device.getName() + "成功！",
								Toast.LENGTH_SHORT).show();
						// btn.setText("断开");
						flag = true; // 连接标志位
						sendData(app);

					} catch (IOException e) {
						try {
							Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT)
									.show();
							_socket.close();
							_socket = null;
						} catch (IOException ee) {
							Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT)
									.show();
						}

						return;
					}

					// 打开接收线程
					try {
						is = _socket.getInputStream(); // 得到蓝牙数据输入流

					} catch (IOException e) {
						Toast.makeText(this, "接收数据失败！", Toast.LENGTH_SHORT).show();
						return;
					}
					if (bThread == false) {
						ReadThread.start();
						bThread = true;
					} else {
						bRun = true;
					}
				} else {
					flag = false; // 连接标志位
				}

		}
	}

	// 消息处理队列
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
				case 0:
					m = (Map) msg.obj;
					break;
				case 1:
					m = (Map) msg.obj;
					//				res = "未签到";
					break;

				case 2:
					m = (Map) msg.obj;
					//				res = "取消交易";
					break;

			}

		}
	};
	// 接收数据线程
	Thread ReadThread = new Thread() {
		int num = 0;
		byte[] buffer = new byte[1024];
		byte[] buffer_new = new byte[1024];
		int parkLen;
		byte check;
		String packtype;
		String packManey;
		String packCode;

		public void run() {
			// 接收线程
			while (true) {
				try {
					try {
						sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (is.available() > 0) {
						// 读取取标准
						num = is.read(buffer_new, 0, 1); // 读入数据
						if (buffer_new[0] == 0x02) {
							try {
								sleep(500);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							// 读取长度
							num = is.read(buffer_new, 0, 2);
							parkLen = ((buffer_new[0] >> 4) & 0x0F) * 1000;
							parkLen += ((buffer_new[0]) & 0x0F) * 100;
							parkLen += ((buffer_new[1] >> 4) & 0x0F) * 10;
							parkLen += (buffer_new[1]) & 0x0F;
							check = buffer_new[0];
							check ^= buffer_new[1];
							// 读取包数据
							num = is.read(buffer, 0, parkLen);
							for (int count = 0; count < parkLen; count++) {
								check ^= buffer[count];
							}
							// 读取结束和校验
							is.read(buffer_new, 0, 2);
							if (buffer_new[0] == 0x03) {
								check ^= buffer_new[0];
								if (check == buffer_new[1]) {
									System.out.println("check Ok");
									packtype = new String(buffer, 0, 2);// 数据包类型码
									if (packtype.equals("03")) {

										packCode = new String(buffer, 2, 2);// 交易类型码
										if(packCode.equals("A1"))
											packCode="消费";
										if(packCode.equals("D1"))
											packCode="签到";
										packManey = new String(buffer, 4, 12);// 交易金额
										String packMoney = String.valueOf((Double.parseDouble(packManey))/100);

										String commodityCode = new String(
												buffer, 16, 15);// 商户编号 ()
										String posMum = new String(buffer, 31,
												4);// POS顺序号 ()
										String terminalNum = new String(buffer,
												35, 8);// 终端编号
										// POS凭单号
										String voucher = new String(buffer, 43,
												6);
										// 卡 号()
										String idCard = new String(buffer, 73,
												21);
										String operator = new String(buffer,
												118, 5);// 操作员号
										// 卡种类（发卡行名称）
										String cardType = new String(buffer,
												168, 12);

										map.put("res", "成功");//结果
										map.put("packtype", packtype);// 数据包类型码
										map.put("packCode", packCode);// 交易类型码
										map.put("packMoney", packMoney);// 交易金额
										map.put("commodityCode", commodityCode.trim());// 商户编号 ()
										map.put("posMum", posMum.trim());// POS顺序号 ()
										map.put("terminalNum", terminalNum);// 终端编号
										map.put("voucher", voucher);// POS凭单号
										map.put("idCard", idCard.trim());// 卡 号()
										map.put("cardType", cardType);// 卡种类（发卡行名称）

										Message msg = handler.obtainMessage();

										msg.obj = map;
										msg.what = 0;
										handler.sendMessage(msg );
										System.out.println("成功");
									} else if (packtype.equals("04")) {
										packManey = new String(buffer,2,2);
										if (packManey.equals("04")) {

											//											res = "未签到";
											Message msg = handler.obtainMessage();
											map.put("res", "未签到");
											msg.obj = map;
											msg.what = 1;
											handler.sendMessage(msg);
										} else if (packManey.equals("05")) {

											Message msg = handler.obtainMessage();
											map.put("res", "取消交易");
											msg.obj = map;
											msg.what = 2;
											handler.sendMessage(msg);
										}
									}

								}
							}

						}

					}
				} catch (IOException e) {
				}
			}
		}
	};
	private Map<String, String> map = new HashMap<String, String>();

	protected static Map<String, String> m = new HashMap<String, String>();

	// 发送数据
	public void sendData(View v) {
		sendData(100);
	}

	public void sendData(double money) {
		// String money = etText.getText().toString().trim();

		String strMoney = String.valueOf(money);
		if (strMoney.length() > 0) {

			// 将参数转为byte
			byte[] bos = { 0x02, 0x00, 0x16, 0x30, 0x30, 0x41, 0x31, 0x30,
					0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
					0x31, 0x03, 0x64 };
			byte[] moneyByte = String.valueOf(money).getBytes();

			System.arraycopy(moneyByte, 0, bos, bos.length - 2
					- moneyByte.length, moneyByte.length);
			// 校验
			byte check = bos[1];
			for (int i = 1; i < bos.length - 2; i++) {
				check ^= bos[i + 1];
			}
			bos[bos.length - 1] = check;
			if (flag == true) {

				try {
					// 获取输出流对象
					OutputStream os = _socket.getOutputStream();
					// 发送消息
					os.write(bos);
					// Toast.makeText(this, "数据发送成功", 0).show();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				Toast.makeText(this, "蓝牙未连接", Toast.LENGTH_LONG).show();
			}

		} else {
			Toast.makeText(this, "请输入数据", Toast.LENGTH_LONG).show();
		}
	}

	// 关闭程序掉用处理部分
	public void onDestroy() {
		super.onDestroy();
		if (_socket != null) // 关闭连接socket
			try {
				_socket.close();
			} catch (IOException e) {
			}
	}
}
